package sorting;

public class InsertionSort
{
    private int[] myData;

    public InsertionSort(int[] data)
    {
        myData = data;
    }
    public static void main(String[] args)
    {
        int[] data = new int[20];
        if (args.length > 20) {
            System.err.println("Not valid for more than 20 entries");
        }
        int i = 0;
        for (String s : args) {
            data[i++] = Integer.parseInt(s);    
        }

        InsertionSort sorter = new InsertionSort(data);
        System.out.println("Before sorting: " + sorter);
        sorter.sort();
        System.out.println("After sorting: " + sorter);
        System.out.println(InsertionSort.getNotes());
    }

    private void sort()
    {
        for (int i = 1; i < myData.length; i++) {
            int key = myData[i];
            int j = i-1;
            while (j >= 0 && myData[j] > key ) {
                myData[j + 1] = myData[j];
                j--;
            }
            
            myData[j + 1] = key;
        }
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        for (int i : myData) {
            sb.append(i + " ");
        }

        return sb.toString();
    }

    public static String getNotes()
    {
        return "The worst case complexity is O(n^2)";
    }


}
